<?php
namespace api\common\model;
use think\Db;
class Member extends \think\Model 
{
    protected $type = [
        'more' => 'array',
    ];
    protected $name = 'member';
    protected $autoWriteTimestamp = true;
    protected $auto = ['ip'];
    protected $update = ['last_login_ip','delete_time'];
    
    public function setIpAttr($value)
    {
        return request()->ip();
    }
    public function setPasswordAttr($value)
    {
        return preg_match("/^(###)/",$value)?$value:st_password($value);
    }
    public function setLastLoginIpAttr($value)
    {
        return request()->ip();
    }
    public function setDeleteTimeAttr($value)
    {
        return empty($value)?0:$value;
    }
    
    
    //查找推荐人信息
    public function findReferee($mobile,$level){
         $member =Db::name('member') ->where('mobile', $mobile)->field('referee_mobile,mobile')->find();
         if(empty($member)){
             return null;
         }
         $referee = Db::name('member') ->where('mobile', $member['referee_mobile'])->field('referee_mobile,mobile')->find();
         
         if ($referee['referee_mobile']==$referee['mobile']&&$level==1){
             return $referee;
         }elseif ($referee['referee_mobile']==$referee['mobile']){
             return null;
         }elseif ($level>1){
             $referee = self::findReferee($referee['mobile'],--$level);
         }else{
             $referee = self::getMember(['mobile'=>$referee['mobile']]);
         }
         return $referee;
    }

    public function getMember($where){        
        $field ='id,real_name,referee_mobile,mobile,company_name,licence_number,legal_person,type,user_status,phone_status,bank_status,referee_moblie_status';
        $result = $this->where($where)->field( $field)->find(); 
        if(empty($result)){
            return null;
        }
        if($result['type']==1){//个人会员
            $field = 'gold_card';
            $memberDetail = new \api\common\model\MemberDetail();
            unset($result['company_name']);
            unset($result['licence_number']);
            unset($result['legal_person']);
            $detail = $memberDetail ->where('mid',$result['id'])->field( $field)->find();
            if(!empty($detail)){
                $vipResult = array_merge($result->getData(),$detail->getData());
            }else {
                $vipResult = $result;
            }
        
        }else {
            unset($result['real_name']);//释放真实姓名
            $field = 'gold_card';
            $companyDetail = new \api\common\model\CompanyDetail();
            $detail = $companyDetail ->where('mid',$result['id'])->field( $field)->find();
            if(!empty($detail)){
                $vipResult = array_merge($result->getData(),$detail->getData());
            }else {
                $vipResult = $result;
            }
        }
        return $vipResult;  
    }
}
